﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SQLite;
using System.Linq;
using System.Text;
using BlobNet.TestsCommon.DataProviderHelpers.Base;

namespace BlobNet.TestsCommon.DataProviderHelpers
{
    public class KVSSqlLiteTestHelper : DbTestHelper
    {
        protected override string GetConnectionString()
        {
            return ConfigurationManager.AppSettings["BlobNet.DefaultProviders.KVSSqlLite.ConnectionString"]; //TODO: FROM CONFIGURATION AND MORE ELEGANT (DI?)
        }

        public override IDbConnection NewConnection()
        {
            string connectionString = GetConnectionString();
            try
            {
                var sqLiteConnection = new SQLiteConnection(connectionString);
                return sqLiteConnection;
            }
            catch (Exception ex)
            {
                string[] strings = connectionString.Split('=');

                SQLiteConnection.CreateFile(strings[1]);

                return new SQLiteConnection(connectionString);
            }
        }

        protected override void AddParameter(IDbCommand command, string paramName, DbType fieldType, int size, object value)
        {
            var parameter = new SQLiteParameter(paramName, value) { DbType = fieldType, Size = size };

            ((SQLiteCommand)command).Parameters.Add(parameter);

        }

        public override bool TableExists(Guid blobDomainId, string tableName)
        {
            bool result = false;
            using (var conn = NewConnection())
            {
                using (var cmd = conn.CreateCommand())
                {
                    string databaseName = ConfigurationManager.AppSettings["DataProviderName"];
                    cmd.CommandText = string.Format("SELECT count(1) FROM {0}.sys.tables WHERE NAME = N'{1}'",
                                                    databaseName, GetBlobDomainObjectName(blobDomainId, tableName));
                    conn.Open();
                    int count = Convert.ToInt32(cmd.ExecuteScalar());

                    result = count > 0;
                }
                conn.Close();
            }

            SQLiteConnection.ClearAllPools();

            return result;
        }

    }
}
